
// TOKEN数据定义
interface Token {
    accessToken: string,
    refreshToken: string,
}

let tokenPrefix: string = ''
let tokenSuffix: string = ''
let storeAccessTokenName: string = 'AccessToken'
let storeRefreshTokenName: string = 'RefreshToken'

/**
 * 安全链接处理
 * @param params
 * @param link
 */
let safeLinkFunc = (params: string, link: string = window.location.href): boolean => {
    try {
        let safeLink = link
        if (Object.prototype.toString.call(params) === '[object String]') {
            safeLink = safeLink.replace(new RegExp(`[?|&]${params}=[%+-_0-9a-zA-z]*`), '')
        } else if (Object.prototype.toString.call(params) === '[object Array]') {
            for (let i = 0, length = params.length; i < length; i++) {
                safeLink = safeLink.replace(new RegExp(`[?|&]${params[i]}=[%+-_0-9a-zA-z]*`), '')
            }
        } else if (Object.prototype.toString.call(params) === '[object Object]') {
            for (let key in params) {
                safeLink = safeLink.replace(new RegExp(`[?|&]${key}=[%+-_0-9a-zA-z]*`), params[key])
            }
        }
        if (link !== safeLink) {
            // 清除历史记录，避免回退
            window.history.forward()
            window.location.href = safeLink
            return false
        }
        return true
    } catch (exception) {
        console.log('[safeLinkFunc]#异常', exception)
        return false
    }
}

/**
 * 获取JWT负载
 * @param jwt
 */
let getJwtPayloadFunc = (jwt: string): any => {
    try {
        let jwtArray = jwt.split('.')
        let jwtPayload = jwtArray[1]
        jwtPayload = JSON.parse(decodeBase64Func(jwtPayload))
        // @ts-ignore
        if (jwtPayload?.user_name) {
            // @ts-ignore
            jwtPayload.user_name = decodeBase64Func(jwtPayload.user_name)
        }
        return jwtPayload
    } catch (exception) {
        console.log('[getJwtPayloadFunc]#异常', exception)
        return null
    }
}

// Base64编码
let encodeBase64Func = (string: string): string => {
    // @ts-ignore
    return $GP.Util.cryptoJS.enc.Base64.stringify($GP.Util.cryptoJS.enc.Utf8.parse(string))
}
// Base64解码
let decodeBase64Func = (string: string): string => {
    // @ts-ignore
    return $GP.Util.cryptoJS.enc.Base64.parse(decodeURIComponent(string)).toString($GP.Util.cryptoJS.enc.Utf8)
}

// region 认证信息处理方法 +++++
/**
 * 设置TOKEN方法
 * @param accessToken
 * @param refreshToken
 */
let setTokenFunc = (accessToken: string = '', refreshToken: string = ''): Token|null => {
    try {
        setLocalTokenFunc(accessToken, refreshToken)
        return getTokenFunc()
    } catch (exception) {
        console.log('[setTokenFunc]#异常', exception)
        return null
    }
}
/**
 * 获取TOKEN方法
 */
let getTokenFunc = (): Token|null => {
    try {
        return getLocalTokenFunc()
    } catch (exception) {
        console.log('[getTokenFunc]#异常', exception)
        return null
    }
}
/**
 * 删除TOKEN方法
 */
let delTokenFunc = (): boolean => {
    try {
        delLocalTokenFunc()
        return true
    } catch (exception) {
        console.log('[delTokenFunc]#异常', exception)
        return false
    }
}
/**
 * 设置本地存储上的TOKEN
 * @param accessToken
 * @param refreshToken
 */
let setLocalTokenFunc = (accessToken: string = '', refreshToken: string = ''): boolean => {
    try {
        if (accessToken) {
            let accessTokenName = getAccessTokenNameFunc()
            accessTokenName && window.localStorage.setItem(accessTokenName, accessToken)
        }
        if (refreshToken) {
            let refreshTokenName = getRefreshTokenNameFunc()
            refreshTokenName && window.localStorage.setItem(refreshTokenName, refreshToken)
        }
        return true
    } catch (exception) {
        console.log('[setLocalTokenFunc]#异常', exception)
        return false
    }
}
/**
 * 从本地存储获取TOKEN
 */
let getLocalTokenFunc = (): Token|null => {
    try {
        let accessTokenName = getAccessTokenNameFunc()
        let accessToken = accessTokenName && window.localStorage.getItem(accessTokenName)
        let refreshTokenName = getRefreshTokenNameFunc()
        let refreshToken = refreshTokenName && window.localStorage.getItem(refreshTokenName)
        console.log('[common@getLocalTokenFunc]TOKEN名称', accessTokenName, refreshTokenName)
        if (accessToken && refreshToken) {
            return {
                accessToken,
                refreshToken
            }
        }
        return null
    } catch (exception) {
        console.log('[common@getLocalTokenFunc]#异常', exception)
        return null
    }
}
/**
 * 从本地存储删除TOKEN
 */
let delLocalTokenFunc = (): boolean => {
    try {
        let accessTokenName = getAccessTokenNameFunc()
        accessTokenName && window.localStorage.removeItem(accessTokenName)
        let refreshTokenName = getRefreshTokenNameFunc()
        refreshTokenName && window.localStorage.removeItem(refreshTokenName)
        return true
    } catch (exception) {
        console.log('[getLocalTokenFunc]#异常', exception)
        return false
    }
}
let setTokenPrefixFunc = (name: string): string => {
    tokenPrefix = name
    return tokenPrefix
}
let setTokenSuffixFunc = (name: string): string => {
    tokenSuffix = name
    return tokenSuffix
}
let setStoreAccessTokenNameFunc = (name: string): string => {
    storeAccessTokenName = name
    return storeAccessTokenName
}
let setStoreRefreshTokenNameFunc = (name: string): string => {
    storeRefreshTokenName = name
    return storeRefreshTokenName
}
/**
 * 获取AccessToken名称
 */
let getAccessTokenNameFunc = (): string => {
    return tokenPrefix + storeAccessTokenName + tokenSuffix
}
/**
 * 获取RefreshToken名称
 */
let getRefreshTokenNameFunc = (): string => {
    return tokenPrefix + storeRefreshTokenName + tokenSuffix
}

let onCallExecuteResultFunc = (funcList: any[], resultList: any[]): any => {
    try {
        // 取得方法名
        let funcName = funcList[funcList.length - 1].method
        for (let index = 0, length = resultList.length; index < length; index++) {
            if (resultList[index].name == funcName && resultList[index].result.length) {
                return resultList[index].result[resultList[index].result.length - 1]
            }
        }
        return null
    } catch (exception) {
        console.log('[onCallExecuteResultFunc]#异常', exception)
        return null
    }
}

/**
 * Base64转文件
 * @param base64
 */
let base64ToFile = function (base64: string, fileName: string = '') {
    try {
        let bstr = null
        let n = null
        let mime = base64.split(",")[0].match(/:(.*?);/)[1] //mime类型 image/png
        let u8arr = null
        if (base64.indexOf(",") > 0) {
            //  ios兼容
            let arr = base64.split(",")
            bstr = atob(arr[1])
        } else {
            bstr = atob(base64)
        }
        n = bstr.length
        u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        // 创建文件
        return new File([u8arr], fileName ? fileName : `${new Date().getTime()}.${mime.split('/')[1]}`, {type: mime})
    } catch (err) {
        console.error("异常", err)
        return null
    }
}

// endregion

export {
    safeLinkFunc,
    getJwtPayloadFunc,
    encodeBase64Func,
    decodeBase64Func,
    setTokenFunc,
    getTokenFunc,
    delTokenFunc,
    setTokenPrefixFunc,
    setTokenSuffixFunc,
    setStoreAccessTokenNameFunc,
    setStoreRefreshTokenNameFunc,
    getAccessTokenNameFunc,
    getRefreshTokenNameFunc,
    onCallExecuteResultFunc,
    base64ToFile,
}
